package com.wuliupai.delivery.wuliupaidelivery.net;

import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;

/**
 * Descriptions：处理网络请求
 * <p>
 * Author：ChenME
 * Date：11/10/2016
 * Email：ibelieve1210@163.com
 */
public class NetConn {

    private final static int CONNECT_TIMEOUT = 30;
    private final static int READ_TIMEOUT = 100;
    private final static int WRITE_TIMEOUT = 80;

    private OkHttpClient.Builder clientBuilder;

    public NetConn() {
        clientBuilder = new OkHttpClient.Builder();
    }

    public Observable<String> call(String url, String aes) {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    FormBody.Builder builder = new FormBody.Builder();
                    if (null != aes) {
                        builder.add("info", aes);
                    }
                    RequestBody requestBody = builder.build();

                    //构建post请求
                    Request request = new Request.Builder().url(url).post(requestBody).build();

                    clientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);//设置连接超时时间
                    clientBuilder.build().newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            LogUtils.log("网络请求发生异常——\t" + e.toString());
                            subscriber.onError(e);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {
                                subscriber.onNext(response.body().string());
                            } else {
                                LogUtils.log("网络请求发生异常——\terrCode："+response.code()+"\terrMsg："+response.message());
                                subscriber.onError(new Exception("网络异常01\t"+response.code()+"\tmsg:"+response.message()));
                            }
                            subscriber.onCompleted();
                        }
                    });
                }
            }
        });
    }
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    public Observable<String> uplaodFiles(String url, Map<String, Object> params) {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);//设置post的参数
                    if (null != params && !params.isEmpty()) {
                        for (Map.Entry<String, Object> entry : params.entrySet()) {
                            Object obj = entry.getValue();
                            if(obj instanceof String){
                                builder.addFormDataPart(entry.getKey(), (String)obj);//设置post的参数
                            }else if(obj instanceof File) {
                                File file = (File) obj;
                                builder.addFormDataPart(entry.getKey(),file.getName(),//如何接收图片，还在研究
                                        RequestBody.create(MEDIA_TYPE_PNG, file));
                            }
                        }
                    }

                    RequestBody requestBody = builder.build();

                    //构建post请求
                    Request request = new Request.Builder().url(url).post(requestBody).build();

                    clientBuilder.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);//设置连接超时时间
                    clientBuilder.build().newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            LogUtils.log("网络请求发生异常——\t" + e.toString());
                            subscriber.onError(e);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {
                                subscriber.onNext(response.body().string());
                            } else {
                                LogUtils.log("网络请求发生异常——\terrCode："+response.code()+"\terrMsg："+response.message());
                                subscriber.onError(new Exception("网络异常"));
                            }
                            subscriber.onCompleted();
                        }
                    });
                }
            }
        });
    }

}
